<template>
	<AssistWarn v-if="requestRoutes.length === 0">
		你没有正在请求的出行
	</AssistWarn>
	<view class="container flex--col" v-else>
			<RouteItem :route="curRequestRoute"  v-if="!!curRequestRoute.travelId" @clickroute="openRouteList"></RouteItem>
			<!-- AssistOption -->
			<AssistOption @changeOption="handleChangeOption" 
						  @changePage="getRequestVolunteerList"
						  :page="page"
						  :pickOptions="pickOptions"
						  :timeOptions="timeOptions">
			</AssistOption>
			
			<!-- 人员列表 -->
			<FigureList :figureList="volunteerList" 
						:status="Service.SERVICE_AVAILABLE"
						@refreshData="getRequestVolunteerList"
						@requestVolunteer="handleRequestVolunteer">
			</FigureList>
			
			<!-- 点击请求志愿者后显示的弹窗 -->		
			<CandidatePanel :requestingVolunteers="requestingVolunteers"
						    @cancelRequestRoute="handleCancelRequestRoute"
							@cancelRequestVolunteer="handleCancelRequestVolunteer"
							></CandidatePanel>
			
			<!-- 点击路线后出现的弹窗 -->
			<RouteList ref="currentRoute" :curRouteId="curRequestRoute.travelId" :routeList="requestRoutes" @changeRoute="changeRoute"  v-if="!!curRequestRoute.travelId"></RouteList>
		</view>
	</view>
</template>

<script>
	import FigureList from "./FigureList.vue"
	import CandidatePanel from "./CandidatePanel.vue"
	import AssistOption from "./AssistOption.vue"
	import RouteItem from "./RouteItem.vue"
	import RouteList from "./RouteList.vue"
	import AssistWarn from "./AssistWarn.vue"
	import * as BlindApi from "@/api/assist/blind.js"
	import { data } from "../../../uni_modules/uview-ui/libs/mixin/mixin";
	import {isEmpty,dateFormat} from "@/utils/util.js"
	import {REFRESH_TRAVEL_REQUEST,REFERSH_TRAVEL_TIMER} from "@/core/constant/event.js"
	import {FORTHWITH_ASSIST_BLIND_PUSH,FORTHWITH_ASSIST_BLIND_OPERATION} from "@/core/constant/WebSocketEvent.js"
	import {location} from "@/utils/geo.js"
	import * as Service from "@/core/constant/service.js"
	
	
	export default{
		name:"AssitBlind",
		components:{
			FigureList,
			AssistOption,
			CandidatePanel,
			RouteItem,
			RouteList,
			AssistWarn,
		},
		data(){
			return{
				volunteerList:[],
				requestingVolunteers:[],
				page:{
					total:0,
					pageSize:5,
					pageNum:1
				},
				curRequestRoute:null,
				requestRoutes:[],
				
				pickOptions:{
					type:1,
					gender:0,
					age:0,
					count:0,
					score:0,
				},
				Service,
			}
		},
		watch:{
			async curRequestRoute(){
				await this.refreshVolunteerList()
			}
		},
		computed:{
			timeOptions(){
				let date = dateFormat("YYYY-mm-dd",new Date())
				const limitedStartTime = new Date(date+" 22:00")
				let startTime = new Date(Date.now() + 60*65*1000)
				let endTime = new Date(Date.now() + 2*60*65*1000)
			
				if(startTime > limitedStartTime){
					startTime = new Date(Date.now() + 8*60*65*1000)
					endTime = new Date(Date.now() + 9*60*65*1000)
				}
				return {
					date:dateFormat("YYYY-mm-dd",startTime),
					startTime:dateFormat("HH:MM",startTime),
					endTime: dateFormat("HH:MM",endTime)
				}
			},
		},
		methods:{	
			/**
			 * 请求： 获取正在请求路线列表
			 */
			async getRequestRouteList(){
				const data =  await BlindApi.requestRoutes()
				this.requestRoutes = data
				return data
			},
			
			/**
			 * 请求：请求志愿者
			 * @param {Object} params
			 */
			async requestVolunteer(params){
				await BlindApi.requestVolunteer(params)
			},
			/**
			 * 请求：获取请求中的志愿者列表
			 * @param {Object} applyStatus
			 */
			async getOnRequestVolunteers(){
				const params = {
					routeId:this.curRequestRoute.routeId,
					applyStatus:1
				} 
				this.requestingVolunteers = await BlindApi.conditionalVolunteersList(params)
			},
			
			/**
			 * 1. 判断正在请求路线是否为空
			 * 2. 请求
			 * 3. 如果请求失败（路线状态错误），则将当前正在路线删除
			 * 
			 * @业务：获取可以请求的志愿者列表
			 */
			async getRequestVolunteerList(pageNum = 1){
				if(this.curRequestRoute === null){
					return
				}
				const params = {
					travelId:this.curRequestRoute.travelId,
					pageNum,
					startTime:`${this.timeOptions.date} ${this.timeOptions.startTime}:00`,
					endTime:`${this.timeOptions.date} ${this.timeOptions.endTime}:00`,
					...this.pickOptions,
					...this.$store.getters.userPosition
				}
				try{
					const data = await BlindApi.volunteersList(params)
					this.volunteerList = data.rows
					this.page.total = data.total
					this.page.pageNum = pageNum
				}catch(error){
					console.log(error)
					if(this.curRequestRoute){
						const index = this.requestRoutes.indexOf(this.curRequestRoute)
						this.requestRoutes.splice(index,1)
						this.curRequestRoute = this.requestRoutes[0] ?? null
					}
				}
			},
			
			/**
			 * 业务：改变当前请求路线
			 * @param {Object} travelId
			 */
			async changeRoute(travelId){
				this.curRequestRoute = this.requestRoutes.find(route => route.travelId === travelId)
				await this.refreshVolunteerList();
			},
			/**
			 * 业务：刷新路线列表
			 * 1. 获取正在请求路线列表
			 * 2. 选择第一个为当前正在请求路线
			 */
			async refreshRouteList(){
				try{
					const data = await this.getRequestRouteList()
					if(isEmpty(data)){
						return 
					}
					this.curRequestRoute = data[0] ?? null
				}catch(err){
					console.log(err)
				}
			},
			/**
			 * 1. 如果改变的是时间，分开赋值。改变的是其他选项，直接赋值
			 * 2. 刷新page
			 * 3. 获取可以请求的志愿者列表
			 * 业务：当筛选条件改变时
			 * @param {Object} option
			 * @param {Object} value
			 */
			async handleChangeOption(option,value){
				if(option === 'time'){
					this.timeOptions.date = value.date
					this.timeOptions.startTime = value.startTime
					this.timeOptions.endTime = value.endTime
				}else{
					this.pickOptions[option] = this.pickOptions[option] !== value?value:0
				}
				this.page.pageNum = 1
				this.page.total = 0
				await this.getRequestVolunteerList()
			},
			/**
			 * 1. 请求志愿者
			 * 2. 将志愿者从志愿者列表中移除
			 * 3. 刷新志愿者列表（请求中的和未请求的）
			 * 业务：当用户点击请求志愿者的按钮
			 * @param {Object} item
			 */
			async handleRequestVolunteer(item){
				const {userId:volunteerId,distance} = item
				const params = {
					volunteerId,
					travelId:this.curRequestRoute.travelId,
					distance
				}
				await this.requestVolunteer(params)
				await this.refreshVolunteerList()
			},
			/**
			 * 业务：刷新志愿者列表（请求中的和未请求的）
			 */
			async refreshVolunteerList(){
				if(this.curRequestRoute === null ){
					return 
				}
				await this.getOnRequestVolunteers()
				await this.getRequestVolunteerList()
			},
			
			/**
			 * 1. 取消当前正在请求的志愿者
			 * 2. 刷新志愿者列表（请求中的和未请求的）
			 * 业务：取消请求志愿者
			 * @param {Object} item
			 */
			async handleCancelRequestVolunteer(item){
				const params = {
					travelId:item.travelId,
					travelApplyId:item.travelApplyId
				}
				await BlindApi.cancelRequestVolunteer(params)
				await this.refreshVolunteerList()
			},
			
			/**
			 * 1. 取消请求路线
			 * 2. 将当前路线从正在请求路线列表中移除
			 * 3. 对curRequestRoute重新取值
			 * 
			 * 业务：取消请求路线
			 */
			async handleCancelRequestRoute(){
				const params = {
					travelId:this.curRequestRoute.travelId
				}
				await BlindApi.cancelRequestRoute(params)
				const index = this.requestRoutes.indexOf(this.curRequestRoute)
				this.requestRoutes.splice(index,1)
				this.curRequestRoute = this.requestRoutes[0] ?? null
			},
			/**
			 * 1. 刷新正在请求路线列表
			 * 2. 如果是接受，则刷新未出行列表
			 * 
			 * 业务：当接收到志愿者对请求的操作的通知
			 * @param {Object} data
			 */
			async handleOnOperationNotice(data){
				await this.refreshRouteList()
				if(data.type === 1){
					uni.$emit(REFERSH_TRAVEL_TIMER)
				}
			},
			/**
			 * 业务：打开请求路线列表弹窗
			 */
			openRouteList(){
				this.$refs.currentRoute.open()
			},
			/**
			 * 初始化页面调用
			 * 业务：刷新志愿者请求列表
			 */
			async refreshRequestList(){
				await this.refreshRouteList()
				await this.refreshVolunteerList()
			},
		},
		async created(){
			uni.$on(REFRESH_TRAVEL_REQUEST,this.refreshRouteList)
			uni.$on(FORTHWITH_ASSIST_BLIND_PUSH,async () => {
				await this.getRequestVolunteerList()
			})
			uni.$on(FORTHWITH_ASSIST_BLIND_OPERATION,async (data) =>{
				await this.handleOnOperationNotice(data)
			})
			// 如果是第一次进入出行页面，则请求，否则无需重新请求
			if(this.curRequestRoute === null){
				await this.refreshRouteList()
			}
		},
		
		
	}
	
</script>

<style lang="scss" scoped>
	
	.container{
		align-items: center;
		// justify-content: center;
		gap:24px;
	}


</style>